package com.deyuanyun.pic.pig.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.deyuanyun.pic.common.dto.Result;
import com.deyuanyun.pic.common.exception.InterfaceCode;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.UploadUtil;

import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.pig.app.mapper.PigMapper;
import com.deyuanyun.pic.pig.app.service.PigService;
import com.deyuanyun.pic.pig.app.support.PigEffectUtil;

import com.deyuanyun.pic.pig.app.domain.PigResults;
import com.deyuanyun.pic.pig.app.domain.PigTaskPoint;
import com.deyuanyun.pic.settings.enumeration.UserState;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.*;

@Service
public class PigServiceImpl implements PigService {

    @Resource
    private PigMapper pigMapper;
    @Value("${File_Server_Path}")
    String fileServerPath;

    /**
     * 判断是否为有效用户
     */
    @Override
    public HashMap<String, Object> findUserId(String UserID) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        try {
            map = pigMapper.findUserId(UserID);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 根据用户名查询相关数据
     *
     * @param Account
     * @return
     * @throws Exception
     */

    private List<HashMap<String, Object>> getUserByAccount(String Account) {

        List<HashMap<String, Object>> maplist = pigMapper.login(Account);
        for (Map map : maplist) {

            if ("out".equals(map.get("A"))) {

                Date startDate = (Date) map.get("startDate".toUpperCase());
                Date endDate = (Date) map.get("endDate".toUpperCase());
                if (startDate == null || endDate == null) {
                    map.put("error", "error");
                } else {
                    Long startTime = startDate.getTime();
                    Long endTime = endDate.getTime();
                    Long currentTime = (new Date()).getTime();
                    if (currentTime < startTime || currentTime > endTime) {
                        map.put("error", "error");
                    }
                }
            }
        }
        return maplist;
    }


    @Override
    public Map<String, Object> getUserName(String Account) {
        Map mapMarks = new HashMap<String, Object>();
        HashMap<String, Object> mapMark = new HashMap<String, Object>();

        try {
            List<HashMap<String, Object>> map = getUserByAccount(Account);

            if (map.size() == 0) {
                mapMarks.put("Code", InterfaceCode.USER_FAIL.getCode());
                mapMarks.put("Msg", InterfaceCode.USER_FAIL.getLabel());

                return mapMarks;
            }

            if (map.size() > 1) {
                mapMarks.put("Code", InterfaceCode.USER_REPEAT.getCode());
                mapMarks.put("Msg", InterfaceCode.USER_REPEAT.getLabel());

                return mapMarks;
            }

            Map<String,Object> map1 = map.get(0);

            if (map1.get("error") != null) {
                mapMarks.put("Code", InterfaceCode.USER_LIMIT.getCode());
                mapMarks.put("Msg", InterfaceCode.USER_LIMIT.getLabel());

                return mapMarks;
            }


            if(!UserState.ACTIVATE.toString().equals(map1.get("STATE"))
                   && "in".equals(map1.get("A"))){
                mapMarks.put("Code", InterfaceCode.USER_FORBIDDEN.getCode());
                mapMarks.put("Msg", InterfaceCode.USER_FORBIDDEN.getLabel());

                return mapMarks;
            }

            mapMarks.put("Code", InterfaceCode.SUCCESS.getCode());
            mapMarks.put("Msg", InterfaceCode.SUCCESS.getLabel());
            mapMark.put("UserName", map.get(0).get("USERNAME"));
            mapMarks.put("Result", mapMark);


        } catch (Exception e) {
            mapMarks.put("Code", InterfaceCode.SERVICE_FAIL.getCode());
            mapMarks.put("Msg", InterfaceCode.SERVICE_FAIL.getLabel());
            e.printStackTrace();
        }
        return mapMarks;
    }

    @Override
    public Map<String, Object> login(String Param) {

        Map mapMarks = new HashMap();
        JSONObject obj = JSON.parseObject(Param);
        String Account = obj.getString("Account").trim();
        String Code = obj.getString("Code");
        String DeviceID = obj.getString("DeviceID");
        Integer accessType = obj.getInteger("DeviceType");
        if (Account == null) {
            mapMarks.put("Code", InterfaceCode.PARAMETER_FAIL.getCode());
            mapMarks.put("Msg", InterfaceCode.PARAMETER_FAIL.getLabel());
            return mapMarks;
        }

        List<HashMap<String, Object>> map = null;
        HashMap<String, Object> mapMark = new HashMap<String, Object>();


        try {
            map = getUserByAccount(Account);
            if (map == null) {
                mapMarks.put("code", InterfaceCode.USER_FAIL.getCode());
                mapMarks.put("msg", InterfaceCode.USER_FAIL.getLabel());
                return mapMarks;
            }

            if (!Code.equals(map.get(0).get("PWD"))) {
                mapMarks.put("Code", InterfaceCode.CODE_FAIL.getCode());
                mapMarks.put("Msg", InterfaceCode.CODE_FAIL.getLabel());
                return mapMarks;
            }
            if (Code != null && Code.equals(map.get(0).get("PWD"))) {
                mapMarks.put("Code", InterfaceCode.SUCCESS.getCode());
                mapMarks.put("Msg", InterfaceCode.SUCCESS.getLabel());
                String userId = (String) map.get(0).get("ID_");
                Map<String, Object> realMap = pigMapper.selectRealName(userId);
                if (realMap != null) {
                    String companyId = realMap.get("CPD").toString();
                    mapMark.put("Corp",selectCompanyName(companyId));
                    mapMark.put("PhoneNum",realMap.get("MOBILE"));
                    mapMark.put("RealName", realMap.get("REALNAME"));
                }
                mapMark.put("UserID", userId);
                mapMarks.put("Result", mapMark);

                String Id = UUID.randomUUID().toString().replaceAll("-", "");
                int status = 0;
                insertLog(Id, userId, status, accessType);

            }

        } catch (Exception e) {
            e.printStackTrace();
            String Id = UUID.randomUUID().toString().replaceAll("-", "");
            String userId = (String) map.get(0).get("ID_");
            int status = 1;
            insertLog(Id, userId, status, accessType);


            mapMarks.put("Code", InterfaceCode.SERVICE_FAIL.getCode());
            mapMarks.put("Msg", InterfaceCode.SERVICE_FAIL.getLabel());

        }


        return mapMarks;
    }


    /**
     * 通过递归查询一级公司名称
     * @param companyId
     * @return
     */
    private String selectCompanyName(String companyId){
        Map<String,Object> map = pigMapper.selectCompanyName(companyId);
        Object parentId = map.get("PARENTID");
        String realName = map.get("SHORTNAME").toString();
        if(ObjectUtil.isNotNullEmpty(parentId)){
            selectCompanyName(parentId.toString());
        }else{
            return realName;
        }
        return realName;
    }



    @Override
    // 异步写入登录日志
    public void insertLog(String Id, String userId, Integer state,
                          Integer accessType) {
        try {
            pigMapper.insertLog(Id, userId, state, accessType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    // 获取任务列表
    public HashMap<String, Object> findTask() throws Exception {
        Page<HashMap<String, Object>> list = null;
        HashMap<String, Object> map = null;
        try {
            list = pigMapper.findTask();
            for (HashMap<String, Object> obj : list) {
                obj.put("Code", obj.get("CODE"));
                obj.remove("CODE");
                obj.put("Name", obj.get("NAME"));
                obj.remove("NAME");
                obj.put("CreateTime", obj.get("CREATEDATE"));
                obj.remove("CREATEDATE");
                obj.put("CreateUser", obj.get("CREATEUSER"));
                obj.remove("CREATEUSER");
                obj.put("CreateRemark", obj.get("CREATEMARK"));
                obj.remove("CREATEMARK");
                obj.put("PipeName", obj.get("PIPENAME"));
                obj.remove("PIPENAME");
                obj.put("SendTime", obj.get("SENDTIME"));
                obj.remove("SENDTIME");
                obj.put("SendAddr", obj.get("PIGGNUMBER"));
                obj.remove("PIGGNUMBER");
                obj.put("BackAddr", obj.get("TOPIGGMUMBER"));
                obj.remove("TOPIGGMUMBER");
                obj.put("PlanTime", obj.get("PLANDATE"));
                obj.remove("PLANDATE");
                obj.put("ActualTime", obj.get("PAGTIME"));
                obj.remove("PAGTIME");
                String type = (String) obj.get("TYPE");
                // 根据type查询是否是检测还是清管
                List<HashMap<String, Object>> list1 = pigMapper
                        .getTaskTypes(type);
                String code = (String) list1.get(0).get("CODE");
                if (code.equals("PIGGING_TYPE_SCQG")
                        || code.equals("PIGGING_TYPE_ZNJCQQG")
                        || code.equals("PIGGING_TYPE_OHTER")) {
                    obj.put("CleanType", 1);
                } else {
                    obj.put("CleanType", 2);
                }

                obj.put("CleanTypeID", obj.get("TYPE"));
                obj.remove("TYPE");
                obj.put("CleanTool",
                        null != obj.get("DETECTORTYPE") ? obj
                                .get("DETECTORTYPE") : obj.get("PIGTYPE"));
                obj.remove("DETECTORTYPE");
                obj.remove("PIGTYPE");
                BigDecimal a = (BigDecimal) obj.get("STAUS");
                if (a.intValue() == 2) {
                    obj.put("Status", 1);
                } else if (a.intValue() == 3) {
                    obj.put("Status", 2);
                }
                obj.remove("STAUS");

            }
            map = new HashMap<String, Object>();
            if (list != null && list.size() > 0) {
                map.put("List", list);
            }
            map.put("PageSize", list.getPageSize());
            map.put("PageNum", list.getPageNum());
            map.put("Total", list.getTotal());

        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        return map;
    }

    @Override
    public HashMap<String, Object> getTaskInfo(String taskId) throws Exception {
        HashMap<String, Object> obj = null;
        HashMap<String, Object> map = null;
        try {
            obj = pigMapper.getTaskInfo(taskId);
            obj.put("Code", obj.get("CODE"));
            obj.remove("CODE");
            obj.put("Name", obj.get("NAME"));
            obj.remove("NAME");
            obj.put("CreateTime", obj.get("CREATEDATE"));
            obj.remove("CREATEDATE");
            obj.put("CreateUser", obj.get("CREATEUSER"));
            obj.remove("CREATEUSER");
            obj.put("CreateRemark", obj.get("CREATEMARK"));
            obj.remove("CREATEMARK");
            obj.put("PipeName", obj.get("PIPENAME"));
            obj.remove("PIPENAME");
            obj.put("SendAddr", obj.get("PIGGNUMBER"));
            obj.remove("PIGGNUMBER");
            obj.put("BackAddr", obj.get("TOPIGGMUMBER"));
            obj.remove("TOPIGGMUMBER");
            obj.put("SendTime", obj.get("CRTIME"));
            obj.remove("CRTIME");
            obj.put("PlanTime", obj.get("PLANDATE"));
            obj.remove("PLANDATE");
            obj.put("ActualTime", obj.get("PAGTIME"));
            obj.remove("PAGTIME");
            String type = (String) obj.get("TYPE");
            List<HashMap<String, Object>> list1 = pigMapper.getTaskTypes(type);
            String code = (String) list1.get(0).get("CODE");
            if ("PIGGING_TYPE_SCQG".equals(code)
                    || "PIGGING_TYPE_ZNJCQQG".equals(code)
                    || "PIGGING_TYPE_OHTER".equals(code)) {
                obj.put("CleanType", 1);
            } else {
                obj.put("CleanType", 2);
            }
            obj.put("CleanTypeID", obj.get("TYPE"));
            obj.remove("TYPE");
            obj.put("CleanTool",
                    null != obj.get("DETECTORTYPE") ? obj.get("DETECTORTYPE")
                            : obj.get("PIGTYPE"));
            obj.remove("DETECTORTYPE");
            obj.remove("PIGTYPE");
            map = new HashMap<String, Object>();
            map.put("List", obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }



    @Override
    // 获取发球点收球点跟踪点列表
    public HashMap<String, Object> findMarker(String taskId) throws Exception {
        List<HashMap<String, Object>> list = null;
        ArrayList<HashMap<String, Object>> list3 = new ArrayList<HashMap<String, Object>>();
        List<HashMap<String, Object>> listType = null;
        HashMap<String, Object> map4 = null;
        try {
            HashMap<String, Object> map = null;
            // 获取发球点列表
            map = pigMapper.findSend(taskId);
            map4 = new HashMap<String, Object>();
            if (map != null) {
                map.put("TaskID", map.get("ID_"));
                map.put("ID", map.get("SENDID"));
                map.put("Code", map.get("SENDCODE"));
                map.put("TaskID", taskId);
                map.put("GisID", map.get("SENDGISID"));
                map.put("Name", map.get("SENDNAME"));
                if (map.get("SENDMILE") != null) {
                    BigDecimal mile = ((BigDecimal) map.get("SENDMILE")).setScale(
                            3, BigDecimal.ROUND_HALF_DOWN);
                    map.put("Mile", mile);
                }

                map.put("RefPoint", map.get("SENDREFPOINT"));
                map.put("User", map.get("SENDUSER"));
                map.put("Region", map.get("REGION"));
                map.put("Time", map.get("SENDTIME"));
                map.put("Remark", map.get("SENDREMARK"));
                map.put("Flow", map.get("SENDFLOW"));
                map.put("OutPressure", map.get("SENDOUTPRESSURE"));
                map.put("InPressure", map.get("SENDINPRESSURE"));
                map.put("PressureGap", map.get("SENDPRESSURE"));
                map.put("Interference", map.get("SENDINTERFERENCE"));
                map.put("PipeDiameter", map.get("PIPEDIAMETER"));
                map.put("CleanTypeID", map.get("TYPE"));
                String type = (String) map.get("TYPE");

                // 判断清管类型
                listType = pigMapper.getTaskTypes(type);
                String code = (String) listType.get(0).get("CODE");
                if ("PIGGING_TYPE_SCQG".equals(code)
                        || "PIGGING_TYPE_ZNJCQQG".equals(code)
                        || "PIGGING_TYPE_OHTER".equals(code)) {
                    map.put("CleanType", 1);
                    map.put("CleanTool", map.get("PIGTYPE"));
                } else {
                    map.put("CleanType", 2);
                    map.put("CleanTool", map.get("DETECTORTYPE"));
                }

                // 根据任务ID算出发球点关联图片地址
                List<HashMap<String, Object>> map5 = pigMapper
                        .selectSpicture(taskId);
                if (map5 != null && map5.size() > 0) {
                    for (int y = 0; y < map5.size(); y++) {
                        HashMap<String, Object> mapz = map5.get(y);
                        String url = (String) mapz.get("URL");
                        String name = (String) mapz.get("NAME");
                        String id = (String) mapz.get("ID");
                        if (url != null && name != null && id != null) {
                            url = fileServerPath + url;
                            mapz.put("Url", url);

                        }
                        mapz.remove("URL");
                        mapz.remove("ID");
                        mapz.remove("NAME");
                    }
                    if (map5 != null && map5.size() > 0) {
                        map.put("Pics", map5);
                    }
                }
                map.remove("ID_");
                map.remove("SENDID");
                map.remove("SENDCODE");
                map.remove("SENDGISID");
                map.remove("SENDNAME");
                map.remove("SENDMILE");
                map.remove("SENDREFPOINT");
                map.remove("SENDUSER");
                map.remove("REGION");
                map.remove("SENDTIME");
                map.remove("SENDREMARK");
                map.remove("SENDFLOW");
                map.remove("SENDOUTPRESSURE");
                map.remove("SENDINPRESSURE");
                map.remove("SENDPRESSURE");
                map.remove("SENDINTERFERENCE");
                map.remove("PIPEDIAMETER");
                map.remove("TYPE");
                map.remove("PIGTYPE");
                map.remove("DETECTORTYPE");
                map4.put("SendPoint", map);
            }

            // 收球点列表
            HashMap<String, Object> map1 = pigMapper.findBack(taskId);
            if (!map1.isEmpty()) {
                map1.put("TaskID", map1.get("ID_"));
                map1.put("ID", map1.get("BACKID"));
                map1.put("Code", map1.get("BACKCODE"));
                map1.put("TaskID", taskId);
                map1.put("GisID", map1.get("BACKGISID"));
                map1.put("Name", map1.get("BACKNAME"));
                if (map1.get("BACKMILE") != null) {
                    BigDecimal mile = ((BigDecimal) map1.get("BACKMILE")).setScale(
                            3, BigDecimal.ROUND_HALF_DOWN);
                    map1.put("Mile", mile);
                }

                map1.put("RefPoint", map1.get("BACKREFPOINT"));
                map1.put("User", map1.get("BACKUSER"));
                map1.put("Time", map1.get("BACKTIME"));
                map1.put("Region", map1.get("REGION"));
                map1.put("Remark", null);
                map1.put("OutPressure", map1.get("BACKOUTPRESSURE"));
                map1.put("InPressure", map1.get("BACKINPRESSURE"));
                map1.put("Flow", map1.get("BACKFLOW"));
                map1.put("MaxPressureGap", map1.get("BACKPUSHPRESSURE"));
                map1.put("DumpGas", map1.get("BACKDUMPGAS"));
                map1.put("GasTemperature", map1.get("BACKTEMPRETURE"));
                map1.put("GasDensity", map1.get("BACKGASDENSITY"));
                map1.put("PassGas", map1.get("BACKPASSGAS"));
                map1.put("WasteWater", map1.get("BACKWASTEWATER"));
                map1.put("Waste", map1.get("BACKWASTE"));
                map1.put("ToolMile", map1.get("BACKTOOLMILE"));
                map1.put("ToolSpeed", map1.get("BACKTOOLSPEED"));
                map1.put("Interference", map1.get("BACKINTERFERENCE"));
                map1.put("CompressFactor", map1.get("COMPRESSFACTOR"));
                map1.put("ToolRemark", null);
                map1.put("CleanTypeID", map1.get("TYPE"));
                String type1 = (String) map1.get("TYPE");

                // 查询是否为清管还是检测
                listType = pigMapper.getTaskTypes(type1);
                String code1 = (String) listType.get(0).get("CODE");
                if ("PIGGING_TYPE_SCQG".equals(code1)
                        || "PIGGING_TYPE_ZNJCQQG".equals(code1)
                        || "PIGGING_TYPE_OHTER".equals(code1)) {
                    map1.put("CleanType", 1);
                    map1.put("DirtyRemark", map1.get("DIRTYREMARK"));
                    map1.put("CleanTool", map1.get("PIGTYPE"));
                } else {
                    map1.put("CleanType", 2);
                    map1.put("CleanTool", map1.get("DETECTORTYPE"));
                }

                // 根据Id算出收球点图片关联地址
                List<HashMap<String, Object>> map7 = pigMapper
                        .selectBpicture(taskId);
                if (map7 != null && map7.size() > 0) {
                    for (int c = 0; c < map7.size(); c++) {
                        HashMap<String, Object> mapz = map7.get(c);
                        String url = (String) mapz.get("URL");
                        String name = (String) mapz.get("NAME");
                        String id = (String) mapz.get("ID");
                        if (url != null && name != null && id != null) {
                            url = fileServerPath + url;
                            mapz.put("Url", url);
                        }
                        mapz.remove("URL");
                        mapz.remove("ID");
                        mapz.remove("NAME");
                    }
                    if (map7 != null && map7.size() > 0) {
                        map1.put("Pics", map7);
                    }
                }
                map1.remove("ID_");
                map1.remove("BACKID");
                map1.remove("BACKCODE");
                map1.remove("BACKGISID");
                map1.remove("BACKNAME");
                map1.remove("BACKMILE");
                map1.remove("BACKREFPOINT");
                map1.remove("BACKUSER");
                map1.remove("BACKTIME");
                map1.remove("REGION");
                map1.remove("BACKOUTPRESSURE");
                map1.remove("BACKINPRESSURE");
                map1.remove("BACKFLOW");
                map1.remove("BACKPUSHPRESSURE");
                map1.remove("BACKDUMPGAS");
                map1.remove("BACKTEMPRETURE");
                map1.remove("BACKGASDENSITY");
                map1.remove("BACKPASSGAS");
                map1.remove("BACKWASTEWATER");
                map1.remove("BACKWASTE");
                map1.remove("BACKTOOLMILE");
                map1.remove("BACKTOOLSPEED");
                map1.remove("BACKINTERFERENCE");
                map1.remove("COMPRESSFACTOR");
                map1.remove("TYPE");
                map1.remove("DIRTYREMARK");
                map1.remove("PIGTYPE");
                map1.remove("DETECTORTYPE");
                map4.put("BackPoint", map1);

            }
            HashMap<String, Object> map2 = null;
            // 先判断收发球点是否逆流
            HashMap<String, Object> result = pigMapper
                    .selectOrderBytaskId(taskId);
            // MRAK点列表
            if (ObjectUtil.isNotNullEmpty(result)) {
                int type = new BigDecimal(result.get("IS_ADVERSE_CURRENT").toString())
                        .intValue();
                list = pigMapper.findMark(taskId, type);
                if (list != null && list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        map2 = new HashMap();
                        Map<String, Object> mapMark = list.get(i);
                        String markId = (String) list.get(i).get("MARKID");
                        String type2 = (String) list.get(i).get("TYPE");
                        String detectortype = (String) list.get(i).get(
                                "DETECTORTYPE");
                        String pigtype = (String) list.get(i).get("PIGTYPE");
                        map2.put("TaskID", mapMark.get("ID_"));
                        map2.put("ID", mapMark.get("MARKID"));
                        map2.put("Code", mapMark.get("MARKCODE"));
                        map2.put("GisID", mapMark.get("MARKGISID"));
                        map2.put("Name", mapMark.get("MARKNAME"));
                        if (mapMark.get("BACKMILE") != null) {
                            BigDecimal mile = ((BigDecimal) mapMark.get("BACKMILE"))
                                    .setScale(3, BigDecimal.ROUND_HALF_DOWN);
                            map2.put("Mile", mile);
                        }
                        map2.put("Region", mapMark.get("REGION"));
                        map2.put("RefPoint", mapMark.get("MARKREFPOINT"));
                        map2.put("User", mapMark.get("MARKUSER"));
                        map2.put("Time", mapMark.get("MARKTIME"));
                        map2.put("ArriveTime", mapMark.get("ARRIVETIME"));
                        map2.put("Remark", mapMark.get("MARKREMARK"));
                        map2.put("CleanTypeID", mapMark.get("TYPE"));
                        map2.put("X", mapMark.get("X"));
                        map2.put("Y", mapMark.get("Y"));

                        // 判断是否为清管还是检测
                        listType = pigMapper.getTaskTypes(type2);
                        String code2 = (String) listType.get(0).get("CODE");
                        if ("PIGGING_TYPE_SCQG".equals(code2)
                                || "PIGGING_TYPE_ZNJCQQG".equals(code2)
                                || "PIGGING_TYPE_OHTER".equals(code2)) {
                            map2.put("CleanType", 1);
                            map2.put("CleanTool", pigtype);
                        } else {
                            map2.put("CleanType", 2);
                            map2.put("CleanTool", detectortype);
                        }

                        // 根据markID求出mark点关联图片
                        List<HashMap<String, Object>> map6 = pigMapper
                                .selectMpicture(markId);
                        if (map6 != null && map6.size() > 0) {
                            for (int d = 0; d < map6.size(); d++) {
                                HashMap<String, Object> mapz = map6.get(d);
                                String url = (String) mapz.get("URL");
                                String name = (String) mapz.get("NAME");
                                String id = (String) mapz.get("ID");
                                if (url != null && name != null && id != null) {
                                    url = fileServerPath + url;
                                    mapz.put("Url", url);
                                }
                                mapz.remove("URL");
                                mapz.remove("ID");
                                mapz.remove("NAME");
                            }
                            if (map6 != null && map6.size() > 0) {
                                map2.put("Pics", map6);
                            }
                        }

                        list3.add(map2);
                    }
                    map4.put("List", list3);
                }
            }


        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map4;
    }

    @Override
    public Result findTaskByName(String pipeName) throws Exception {
        return null;
    }

    @Override
    public Result getTaskTypes() throws Exception {
        List<HashMap<String, Object>> code = null;
        String type = null;
        try {
            code = pigMapper.getTaskTypes(type);
        } catch (Exception e) {

            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        return new Result(code);

    }

    @Override
    // 发球点接口
    public void insertSendInfo(PigResults result) throws Exception {
        HashMap<String, Object> map = null;
        Connection conn1 = null;
        long lastDay;

        String taskId = result.getPiggngTaskId();
        BigDecimal staus = new BigDecimal(3);
        Date time = result.getSendBallsTime();
        pigMapper.updateStaus(staus, time, taskId);
        map = pigMapper.selectTime();
        if (map != null && map.size() > 0) {
            Date pagTime = (Date) map.get("PAGTIME");
            // 判断是否为第一个任务，如果为第一个任务，那么pagTime一定为null,因为暂时没有任务完成
            if (pagTime == null) {

                lastDay = 0;
                result.setLastLimitDays(lastDay);

            } else {
                lastDay = (Long) ((time.getTime() - pagTime.getTime()) / 86400000);
                result.setLastLimitDays(lastDay);
            }

        }
        pigMapper.updateSendInfo(result);
        pigMapper.updateCleanType(result);

    }

    @Override
    // 收球点接口
    public void updateBackInfo(PigResults result) throws Exception {
        Connection conn = null;

        // conn.setAutoCommit(false);
        String taskId = result.getPiggngTaskId();

        // 获取管道内径
        HashMap<String, Object> map = pigMapper.findSend(taskId);
        result.setInterDiameter((BigDecimal) map.get("PIPEDIAMETER"));

        // 获取清管效率
        BigDecimal pigginGefficiency = this.clearLineefficient(result);
        result.setPigginGefficiency(pigginGefficiency);

        // 根据清管效率得出清管效果
        PigResults pr = this.getPiggingEffict(result);
        String pigginGeffict = pr.getPigginGeffict();
        result.setPigginGeffict(pigginGeffict);
        pigMapper.updateBackInfo(result);
        // pigMapper.updateCleanType(result);

        Date time = null;
        BigDecimal staus = new BigDecimal(4);
        pigMapper.updateStaus(staus, time, taskId);

        // conn.commit();

    }

    @Override
    // mark点接口
    public void updateMarker(PigTaskPoint point) throws Exception {

        String taskId = point.getPiggngTaskId();

        Date passTime = point.getPassTime();

        BigDecimal mile = point.getMile();

        String ID = point.getId();

        BigDecimal avgspeed = null;

        //算出上个mark点的最大时间和距离 time和markMile
        HashMap<String, Object> map = pigMapper.selectSpeed(taskId);

        //每次任务第一次mark点的通过时间和发球点的时间 maxTime和sendTime
        HashMap<String, Object> maps = pigMapper.MaxSpeed(taskId);

        HashMap<String, Object> mapss = pigMapper.selectAvgSpeed(ID);

        // 先判断收发球点是否逆流
        HashMap<String, Object> result = pigMapper.selectOrderBytaskId(taskId);
        // MRAK点列表
        int istype = new BigDecimal(result.get("IS_ADVERSE_CURRENT").toString()).intValue();
        BigDecimal avgSpeed = methodAvgSpeed(maps, map, passTime, avgspeed,
                mile);
        if (mapss.get("avg_speed".toUpperCase()) != null) {

            pigMapper.updateMarker(point);
        } else {
            point.setAvgSpeed(avgSpeed);

            pigMapper.updateMarker(point);
        }
        if (istype == 0) {

            List<HashMap<String, Object>> maplist = pigMapper
                    .selectOtherMarkByMile(taskId, mile);
            if (maplist != null && maplist.size() > 0) {
                for (int i = 0; i < maplist.size(); i++) {
                    HashMap<String, Object> mapMark = maplist.get(i);
                    PigTaskPoint point1 = new PigTaskPoint();
                    point1.setId(mapMark.get("ID_").toString());
                    point1.setAvgSpeed(avgSpeed);
                    pigMapper.updateMarker(point1);
                }
            }
        } else {

            List<HashMap<String, Object>> maplist = pigMapper
                    .selectNiOtherMarkByMile(taskId, mile);
            if (maplist != null && maplist.size() > 0) {
                for (int i = 0; i < maplist.size(); i++) {
                    HashMap<String, Object> mapMark = maplist.get(i);
                    PigTaskPoint point1 = new PigTaskPoint();
                    point1.setId(mapMark.get("ID_").toString());
                    point1.setAvgSpeed(avgSpeed);
                    pigMapper.updateMarker(point1);
                }
            }
        }

    }

    @Override
    // 人到达接口
    public void arriveMark(PigTaskPoint point) throws Exception {

        pigMapper.arriveMark(point);

    }

    @Override
    // 获取清管系统配置
    public HashMap<String, Object> getConfigs() throws Exception {
        HashMap<String, Object> map1 = new HashMap<String, Object>();
        HashMap<String, Object> map2 = new HashMap<String, Object>();
        try {
            List<HashMap<String, Object>> list1 = pigMapper.getdetector();
            String a = null;
            List<HashMap<String, Object>> list2 = pigMapper.getTaskTypes(a);

            for (HashMap<String, Object> obj : list2) {
                if (obj.get("CODE").equals("PIGGING_TYPE_SCQG")
                        || obj.get("CODE").equals("PIGGING_TYPE_ZNJCQQG")
                        || obj.get("CODE").equals("PIGGING_TYPE_OHTER")) {
                    obj.put("Type", 1);
                    obj.put("Name", obj.get("NAME"));
                    obj.remove("CODE");
                    obj.remove("NAME");
                } else {
                    obj.put("Type", 2);
                    obj.put("Name", obj.get("NAME"));
                    obj.remove("NAME");
                    obj.remove("CODE");
                }
            }
            for (HashMap<String, Object> obj : list1) {
                obj.put("Name", obj.get("NAME"));
                obj.remove("NAME");
            }
            map1.put("DetectorList", list1);
            map1.put("List", list2);
            map2.put("CleanTypeConfig", map1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map2;
    }

    /**
     * 发球点收球点Mark点通过接口（1为发球点 2为标记点 3为收球点）
     */

    @Override
    public void passBall(String taskId, String ID, Date passTime,
                         BigDecimal mile, int type) throws Exception {

        int type1 = type;
        BigDecimal avgspeed = null;

        if (type1 == 1) {
            pigMapper.updateSend(taskId, passTime);
        } else if (type1 == 2) {

            HashMap<String, Object> map = pigMapper.selectSpeed(taskId);

            HashMap<String, Object> maps = pigMapper.MaxSpeed(taskId);

            HashMap<String, Object> mapss = pigMapper.selectAvgSpeed(ID);
            // 先判断收发球点是否逆流
            HashMap<String, Object> result = pigMapper
                    .selectOrderBytaskId(taskId);
            // MRAK点列表
            int istype = new BigDecimal(result.get("IS_ADVERSE_CURRENT").toString())
                    .intValue();
            BigDecimal avgSpeed = methodAvgSpeed(maps, map, passTime, avgspeed,
                    mile);

            PigTaskPoint point = new PigTaskPoint();
            if (mapss.get("avg_speed".toUpperCase()) != null) {
                point.setId(ID);
                point.setPassTime(passTime);
                pigMapper.updateMarker(point);
            } else {
                point.setAvgSpeed(avgSpeed);
                point.setId(ID);
                point.setPassTime(passTime);
                pigMapper.updateMarker(point);
            }
            if (istype == 0) {

                List<HashMap<String, Object>> maplist = pigMapper
                        .selectOtherMarkByMile(taskId, mile);
                addAvgSpeed(maplist, avgSpeed);

            } else {

                List<HashMap<String, Object>> maplist = pigMapper
                        .selectNiOtherMarkByMile(taskId, mile);
                addAvgSpeed(maplist, avgSpeed);

            }

        } else if (type1 == 3) {

            HashMap<String, Object> map = pigMapper.selectSpeed(taskId);

            HashMap<String, Object> maps = pigMapper.MaxSpeed(taskId);

            // 先判断收发球点是否逆流
            HashMap<String, Object> result = pigMapper
                    .selectOrderBytaskId(taskId);
            // MRAK点列表
            int istype = new BigDecimal(result.get("IS_ADVERSE_CURRENT").toString())
                    .intValue();
            HashMap<String, Object> map1 = pigMapper.findBack(taskId);

            BigDecimal avgSpeed = null;

            if (map1.get("BACKMILE") != null) {
                mile = ((BigDecimal) map1.get("BACKMILE")).setScale(
                        3, BigDecimal.ROUND_HALF_DOWN);

                avgSpeed  = methodAvgSpeed(maps, map, passTime, avgspeed,
                        mile);

                if (istype == 0) {

                    List<HashMap<String, Object>> maplist = pigMapper
                            .selectOtherMarkByMile(taskId, mile);
                    addAvgSpeed(maplist, avgSpeed);

                } else {

                    List<HashMap<String, Object>> maplist = pigMapper
                            .selectNiOtherMarkByMile(taskId, mile);
                    addAvgSpeed(maplist, avgSpeed);

                }
            }

            pigMapper.updateBack(taskId, passTime, new Date(),avgSpeed);

        }

    }

    private void addAvgSpeed(List<HashMap<String, Object>> maplist, BigDecimal avgSpeed) {
        if (maplist != null && maplist.size() > 0 && avgSpeed != null) {
            for (int i = 0; i < maplist.size(); i++) {
                HashMap<String, Object> mapMark = maplist.get(i);
                PigTaskPoint point1 = new PigTaskPoint();
                point1.setId(mapMark.get("ID_").toString());
                point1.setAvgSpeed(avgSpeed);
                pigMapper.updateMarker(point1);
            }
        }
    }

    @SuppressWarnings("rawtypes")
    private static PigResults getPiggingEffict(PigResults pr) throws Exception {
        Class c = pr.getClass();
        Field f = c.getDeclaredField("pigginGeffict");
        f.setAccessible(true);
        f.set(pr,
                clearLineefficient(pr).compareTo(BigDecimal.valueOf(0.9)) >= 0.9 ? "良好"
                        : "非良好");
        return pr;
    }

    private static BigDecimal isBigDecimalNull(BigDecimal inNum) {
        return StringUtils.isEmpty(inNum) ? BigDecimal.valueOf(0) : inNum;
    }

    /**
     * 得到清管效率
     *
     * @param pig
     * @return
     */
    private static BigDecimal clearLineefficient(PigResults pig) {
        BigDecimal actualPassgasVolume = isBigDecimalNull(pig
                .getActualPassGasVolume());// 管道实际通过气量
        BigDecimal gaasRelativedEnsity = isBigDecimalNull(pig
                .getGasRelativedEnsity());// 天然气相对密度
        BigDecimal avgTempreture = isBigDecimalNull(pig.getAvgTempreture());// 天然气平均温度
        BigDecimal pigRunLength = isBigDecimalNull(pig.getPigRunLength());// 清管器运行距离
        BigDecimal compressionCoefficient = isBigDecimalNull(pig
                .getCompressionCoefficient());// 在平均压力下的压缩系数
        BigDecimal interDiameter = isBigDecimalNull(pig.getInterDiameter());// 管道内径
        BigDecimal sendBallPressure = isBigDecimalNull(pig
                .getTheBallsPressureFrom());// 发球站压力
        BigDecimal backBallsPressure = isBigDecimalNull(pig
                .getTheBallsPressureTo());// 收球站压力

        // t2= 管道内径 ^(8/3) x 5033.12
        double t2 = 5033.12 * Math.pow(interDiameter.doubleValue(), 8 / 3.0);

        // t= 天然气相对密度 x 天然气平均温度 x 清管器运行距离 x 在平均压力下的压缩系数
        BigDecimal t = gaasRelativedEnsity.multiply(avgTempreture)
                .multiply(pigRunLength).multiply(compressionCoefficient);

        // t=管道实际通过气量 X t ^(1/2)
        t = actualPassgasVolume.multiply(new BigDecimal(Math.pow(
                t.doubleValue(), 0.5)));

        // t3= (发球站压力 ^2 -收球站压力^2)^(1/2)
        Double t3 = Math.pow(
                sendBallPressure.pow(2).subtract(backBallsPressure.pow(2))
                        .doubleValue(), 0.5);

        // t4=t2 X t3(将t2.t3转化为string,防止出现精度损失和NumberFormatException)
        BigDecimal t4 = new BigDecimal(Double.toString(t2))
                .multiply(new BigDecimal(Double.toString(t3)));

        if (t4.doubleValue() == 0) {
            return new BigDecimal(0);
        }

        return t.divide(t4, 5, BigDecimal.ROUND_DOWN);

    }

    private static BigDecimal methodAvgSpeed(HashMap<String, Object> maps,
                                             HashMap<String, Object> map, Date passTime, BigDecimal avgspeed,
                                             BigDecimal mile) {
        // 第一次Mark点球通过的时候
        if (maps != null && maps.get("MAXTIME") == null) {

            // 获取发球时间（因为当前任务第一个Mark点通过的时候，平均速度由当前Mark的绝对距离/（通过时间-发球时间）
            Date time = (Date) maps.get("SENDTIME");
            // 如果没有发球，直接跟踪点全部平均速度是null
            if (time == null) {
                return null;
            }
            BigDecimal newTime = new BigDecimal(
                    (passTime.getTime() - time.getTime()) / 1000);
            if (newTime.intValue() != 0) {
                avgspeed = mile.divide(newTime, 6, BigDecimal.ROUND_HALF_EVEN);
            }
        }
        if (map != null && map.get("MARKMILE") != null
                && map.get("TIME") != null) {
            BigDecimal nowMile = (BigDecimal) map.get("MARKMILE");
            Date time = (Date) map.get("TIME");
            // 这里用不用把Math.abs()转化成String,从而防止精度问题出现，但考虑到后面用除法所以不用考虑
            BigDecimal newMile = new BigDecimal(Math.abs(mile.subtract(nowMile)
                    .doubleValue()));

            BigDecimal newTime = new BigDecimal(
                    (passTime.getTime() - time.getTime()) / 1000);
            if (newTime.intValue() != 0) {
                avgspeed = newMile.divide(newTime, 6,
                        BigDecimal.ROUND_HALF_EVEN);
            }
        }
        return avgspeed;
    }

}